<template>
  <div class="page-container router-view-container">
    <!-- 页面头部 -->
    <PageHeader title="房屋成本管理" :subtitle="`总数: ${state.totalItems}`">
      <!-- 搜索和筛选区域 -->
      <template #search-filters>
        <div class="cost-search">
          <span class="label">成本描述：</span>
          <el-input
            v-model="searchKeyword"
            placeholder="请输入成本描述搜索"
            style="width: 300px"
            clearable
            @input="handleSearch"
          >
            <template #prefix>
              <el-icon><Search /></el-icon>
            </template>
          </el-input>
        </div>
        
        <div class="cost-status-select">
          <span class="label">状态：</span>
          <el-select
            v-model="searchParams.zt"
            placeholder="状态"
            clearable
            style="width: 150px"
            @change="handleFilterChange"
          >
            <el-option label="全部" value="" />
            <el-option label="活动" :value="1" />
            <el-option label="无效" :value="0" />
            <el-option label="历史" :value="2" />
          </el-select>
        </div>
      </template>

      <!-- 主要操作按钮 -->
      <template #main-actions>
        <el-button type="primary" @click="handleAdd">
          <el-icon><Plus /></el-icon>
          新增成本
        </el-button>
      </template>

      <!-- 更多操作下拉菜单 -->
      <template #more-actions>
        <!-- 空内容 -->
      </template>
    </PageHeader>

    <!-- 数据表格 -->
    <div class="table-container">
      <BaseTable
        table-name="cost-table"
        :columns="tableColumns"
        :data="state.pageData"
        :loading="state.loading"
        :sort="sort"
        @sort-change="handleSortChange"
      >
        <!-- 成本描述 -->
        <template #cbms="{ row }">
          <span class="cost-description">{{ row.cbms || '-' }}</span>
        </template>
        
        <!-- 总成本 -->
        <template #zcb="{ row }">
          <span class="cost-amount">¥{{ formatCurrency(row.zcb) }}</span>
        </template>
        
        <!-- 成本日期 -->
        <template #cbrq="{ row }">
          <span class="date-text">{{ formatDate(row.cbrq) }}</span>
        </template>
        
        <!-- 版本 -->
        <template #bb="{ row }">
          <el-tag type="info" size="small">
            版本{{ row.bb }}
          </el-tag>
        </template>
        
        <!-- 状态 -->
        <template #zt="{ row }">
          <el-tag
            :type="getStatusTagType(row.zt)"
            size="small"
          >
            {{ getStatusText(row.zt) }}
          </el-tag>
        </template>
        
        <!-- 创建时间 -->
        <template #cjrq="{ row }">
          <span class="date-text">{{ formatDate(row.cjrq) }}</span>
        </template>
        
        <!-- 操作 -->
        <template #actions="{ row }">
          <div class="action-buttons">
            <el-button
              type="primary"
              size="small"
              @click="handleEdit(row)"
            >
              编辑
            </el-button>
            <el-button
              type="success"
              size="small"
              @click="handleDetail(row)"
            >
              明细
            </el-button>
            <el-button
              type="danger"
              size="small"
              @click="handleDelete(row)"
            >
              删除
            </el-button>
          </div>
        </template>
      </BaseTable>
    </div>
    
    <!-- 分页 -->
    <div class="pagination-wrapper">
      <el-pagination
        v-model:current-page="state.currentPage"
        v-model:page-size="state.pageSize"
        :total="state.totalItems"
        :page-sizes="[10, 20, 50, 100]"
        layout="total, sizes, prev, pager, next, jumper"
        background
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>
    
    <!-- 新增/编辑对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="dialogTitle"
      width="600px"
      class="management-dialog"
      @close="handleDialogClose"
    >
      <el-form
        ref="formRef"
        :model="formData"
        :rules="formRules"
        label-width="100px"
        class="dialog-form"
      >
        <el-form-item label="成本描述" prop="cbms">
          <el-input
            v-model="formData.cbms"
            placeholder="请输入成本描述"
            maxlength="500"
            show-word-limit
            type="textarea"
            :rows="3"
          />
        </el-form-item>
        
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="总成本" prop="zcb">
              <el-input-number
                v-model="formData.zcb"
                placeholder="请输入总成本"
                :min="0"
                :precision="2"
                :disabled="!!formData.id"
                style="width: 100%"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="成本日期" prop="cbrq">
              <el-date-picker
                v-model="formData.cbrq"
                type="date"
                placeholder="选择成本日期"
                format="YYYY-MM-DD"
                value-format="YYYY-MM-DD"
                style="width: 100%"
              />
            </el-form-item>
          </el-col>
        </el-row>
        
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="版本" prop="bb">
              <el-input
                v-model="formData.bb"
                placeholder="请输入版本（支持字母和数字）"
                maxlength="20"
                show-word-limit
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="状态" prop="zt">
              <el-select
                v-model="formData.zt"
                placeholder="请选择状态"
                style="width: 100%"
              >
                <el-option label="活动" :value="1" />
                <el-option label="无效" :value="0" />
                <el-option label="历史" :value="2" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleSubmit">确定</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted, watch } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Search, Plus } from '@element-plus/icons-vue'
import BaseTable from '@/components/tools/BaseTable.vue'
import useTable from '@/composables/useTable.js'
import { costApi } from '@/api/costApi.js'
import { formatDate } from '@/utils/formatter.js'
import PageHeader from '@/components/layout/PageHeader.vue'

// 路由
const router = useRouter()

// 使用通用表格组合式API
const { state, loadData, handleSortChange, updateSearchParams, resetSearchParams, setSearchKeyword, handleSizeChange, handleCurrentChange } = useTable(fetchCostData)

// 搜索关键词
const searchKeyword = ref('')

// 搜索参数
const searchParams = reactive({
  cbms: '',
  zt: ''
})

// 排序
const sort = ref({})

// 搜索处理
const handleSearch = () => {
  updateSearchParams({ cbms: searchKeyword.value })
  loadData()
}

// 筛选处理
const handleFilterChange = () => {
  updateSearchParams(searchParams)
  loadData()
}

// 表格列配置
const tableColumns = [
  { prop: 'cbms', label: '成本描述', minWidth: 200, slot: 'cbms', visible: true },
  { prop: 'zcb', label: '总成本', width: 120, slot: 'zcb', visible: true },
  { prop: 'cbrq', label: '成本日期', width: 140, slot: 'cbrq', visible: true },
  { prop: 'bb', label: '版本', width: 100, slot: 'bb', visible: true },
  { prop: 'zt', label: '状态', width: 100, slot: 'zt', visible: true },
  { prop: 'cjrq', label: '创建时间', width: 140, slot: 'cjrq', visible: true },
  { prop: 'actions', label: '操作', width: 150, slot: 'actions', fixed: 'right', visible: true }
]

// 对话框相关
const dialogVisible = ref(false)
const dialogTitle = ref('')
const formRef = ref()
const formData = reactive({
  id: null,
  cbms: '',
  zcb: 0,
  cbrq: '',
  bb: '1',
  zt: 1
})

// 表单验证规则
const formRules = {
  cbms: [
    { required: true, message: '请输入成本描述', trigger: 'blur' },
    { max: 500, message: '成本描述不能超过500个字符', trigger: 'blur' }
  ],
  zcb: [
    { required: true, message: '请输入总成本', trigger: 'blur' },
    { type: 'number', min: 0, message: '总成本必须大于0', trigger: 'blur' }
  ],
  cbrq: [
    { required: true, message: '请选择成本日期', trigger: 'change' }
  ],
  bb: [
    { required: true, message: '请输入版本', trigger: 'blur' },
    { max: 20, message: '版本不能超过20个字符', trigger: 'blur' }
  ],
  zt: [
    { required: true, message: '请选择状态', trigger: 'change' }
  ]
}

// 数据获取函数
async function fetchCostData(params) {
  try {
    console.log('请求参数:', params)
    const response = await costApi.getCosts(params)
    console.log('API响应:', response)
    
    return response
  } catch (error) {
    console.error('数据获取失败:', error)
    console.error('错误详情:', {
      message: error.message,
      status: error.response?.status,
      data: error.response?.data
    })
    return {
      content: [],
      total: 0
    }
  }
}





// 新增处理
const handleAdd = () => {
  dialogTitle.value = '新增成本'
  resetForm()
  dialogVisible.value = true
}

// 编辑处理
const handleEdit = (row) => {
  dialogTitle.value = '编辑成本'
  Object.assign(formData, row)
  // 编辑时总成本字段将被禁用，保持原值
  dialogVisible.value = true
}

// 明细处理
const handleDetail = (row) => {
  router.push({
    name: 'cost-detail-management',
    params: { fycbId: row.id }
  })
}

// 删除处理
const handleDelete = async (row) => {
  try {
    await ElMessageBox.confirm(
      `确定要删除成本记录 "${row.cbms}" 吗？`,
      '确认删除',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    
    await costApi.deleteCost(row.id)
    ElMessage.success('删除成功')
    loadData()
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('删除失败')
    }
  }
}

// 提交处理
const handleSubmit = async () => {
  try {
    await formRef.value.validate()
    
    // 如果设置为活动状态，需要将其他活动状态的记录设置为历史
    if (formData.zt === 1) {
      try {
        await ElMessageBox.confirm(
          '设置为活动状态将把其他活动状态的成本记录更新为历史状态，是否继续？',
          '确认操作',
          {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          }
        )
        
        // 获取所有成本记录
        const allCosts = await costApi.getAllCosts()
        
        // 找到其他状态为活动的记录（排除当前编辑的记录）
        const activeCosts = allCosts.data.filter(cost => 
          cost.id !== formData.id && cost.zt === 1
        )
        
        // 将这些活动状态的记录更新为历史状态
        if (activeCosts.length > 0) {
          const updatePromises = activeCosts.map(cost => 
            costApi.updateCost(cost.id, { ...cost, zt: 2 })
          )
          await Promise.all(updatePromises)
          ElMessage.success(`已将 ${activeCosts.length} 条活动记录更新为历史状态`)
        }
      } catch (error) {
        if (error === 'cancel') {
          return
        }
        ElMessage.error('更新其他记录状态失败')
        return
      }
    }
    
    if (formData.id) {
      // 更新
      await costApi.updateCost(formData.id, formData)
      ElMessage.success('更新成功')
    } else {
      // 新增
      await costApi.createCost(formData)
      ElMessage.success('创建成功')
    }
    
    dialogVisible.value = false
    loadData()
  } catch (error) {
    ElMessage.error(`操作失败: ${error.message || '未知错误'}`)
  }
}

// 对话框关闭处理
const handleDialogClose = () => {
  resetForm()
}

// 重置表单
const resetForm = () => {
  Object.assign(formData, {
    id: null,
    cbms: '',
    zcb: 0,
    cbrq: '',
    bb: '',
    zt: 1
  })
  formRef.value?.clearValidate()
}

// 格式化货币
const formatCurrency = (amount) => {
  return Number(amount).toLocaleString('zh-CN', {
    minimumFractionDigits: 2,
    maximumFractionDigits: 2
  })
}

// 获取状态文本
const getStatusText = (status) => {
  const statusMap = {
    0: '无效',
    1: '活动',
    2: '历史'
  }
  return statusMap[status] || '未知'
}

// 获取状态标签类型
const getStatusTagType = (status) => {
  const typeMap = {
    0: 'danger',   // 无效 - 红色
    1: 'success',  // 活动 - 绿色
    2: 'info'      // 历史 - 灰色
  }
  return typeMap[status] || 'default'
}

// 初始化
onMounted(() => {
  loadData()
})
</script>

<style scoped>
@import '@/styles/page.css';

/* 搜索筛选样式 */
.cost-search,
.cost-status-select {
  display: flex;
  align-items: center;
  gap: 8px;
}

.label {
  font-size: 14px;
  color: var(--text-secondary, #606266);
  white-space: nowrap;
}

/* 表格容器样式 */
.table-container {
  flex: 1;
  width: 100%;
  min-height: 0;
  max-width: 100%;
  background: white;
  border-radius: 10px;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.05);
  border: 1px solid rgba(0, 0, 0, 0.05);
  padding: 20px;
  display: flex;
  flex-direction: column;
  overflow: hidden;
  box-sizing: border-box;
}

.table-container .base-table-container {
  flex: 1;
  width: 100%;
  min-height: 0;
  max-width: 100%;
  display: flex;
  flex-direction: column;
  box-sizing: border-box;
}

/* 表格样式与主题协调 */
:deep(.el-table) {
  width: 100% !important;
  border-radius: 8px;
  overflow: hidden;
}

:deep(.el-table__header) {
  background: var(--primary-color, #409eff);
}

:deep(.el-table__header th) {
  background: var(--primary-color, #409eff) !important;
  color: white !important;
  font-weight: 600;
  padding: 5px !important;
}

:deep(.el-table__body td) {
  padding: 5px !important;
  border-bottom: 1px solid var(--border-light, #ebeef5);
  font-weight: normal;
  color: #303133;
}

:deep(.el-table--striped .el-table__body tr.el-table__row--striped td) {
  background: var(--table-stripe-background, #fafafa);
}

:deep(.el-table__body tr:hover) {
  background-color: rgba(64, 158, 255, 0.1);
}

/* 分页器样式 */
.pagination-wrapper {
  padding: 20px;
  background: white;
  display: flex;
  justify-content: center;
  align-items: center;
  border-top: 1px solid #e4e7ed;
  box-shadow: 0 -2px 8px rgba(0, 0, 0, 0.05);
  margin-top: 10px;
  border-radius: 0 0 8px 8px;
}

.pagination-wrapper .el-pagination {
  --el-pagination-bg-color: transparent;
  --el-pagination-text-color: #606266;
  --el-pagination-border-radius: 4px;
  --el-pagination-button-color: #606266;
  --el-pagination-button-bg-color: #ffffff;
  --el-pagination-button-disabled-color: #c0c4cc;
  --el-pagination-button-disabled-bg-color: #ffffff;
  --el-pagination-hover-color: #409eff;
  --el-pagination-hover-bg-color: #ecf5ff;
}

.pagination-wrapper .el-pagination .el-pager li {
  border-radius: 4px;
  margin: 0 2px;
  transition: all 0.3s ease;
}

.pagination-wrapper .el-pagination .el-pager li.is-active {
  background-color: #409eff;
  color: white;
  font-weight: 600;
}

.pagination-wrapper .el-pagination .el-pager li:hover {
  background-color: #ecf5ff;
  color: #409eff;
}

.pagination-wrapper .el-pagination .btn-prev,
.pagination-wrapper .el-pagination .btn-next {
  border-radius: 4px;
  margin: 0 4px;
  transition: all 0.3s ease;
}

.pagination-wrapper .el-pagination .btn-prev:hover,
.pagination-wrapper .el-pagination .btn-next:hover {
  background-color: #ecf5ff;
  color: #409eff;
}

.pagination-wrapper .el-pagination .el-pagination__sizes {
  margin-right: 15px;
}

.pagination-wrapper .el-pagination .el-pagination__jump {
  margin-left: 15px;
}

.reset-button {
  display: flex;
  align-items: center;
  gap: 4px;
}

.action-buttons {
  display: flex;
  gap: 8px;
  align-items: center;
}

.cost-description {
  font-weight: 500;
  color: var(--text-color);
  max-width: 180px;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
  display: inline-block;
}

.cost-amount {
  font-weight: 600;
  color: #e6a23c;
  font-size: 14px;
}

.date-text {
  color: #666;
  font-size: 12px;
}

:deep(.el-table) {
  border-radius: 8px;
  overflow: hidden;
}

:deep(.el-table th) {
  background-color: var(--primary-color) !important;
  color: #ffffff !important;
  font-weight: 600 !important;
}

:deep(.el-table__header) {
  background-color: var(--primary-color) !important;
}

:deep(.el-table__header th) {
  background-color: var(--primary-color) !important;
  color: #ffffff !important;
  font-weight: 600 !important;
}

:deep(.el-table td) {
  padding: 12px 0;
}

:deep(.el-dialog__body) {
  padding: 20px;
}

:deep(.el-form-item) {
  margin-bottom: 20px;
}

:deep(.el-tag) {
  border-radius: 4px;
}

/* 响应式调整 */
@media (max-width: 768px) {
  .table-container {
    padding: 8px;
  }
  
  .pagination-wrapper {
    padding: 10px;
  }
  
  .pagination-wrapper .el-pagination {
    font-size: 12px;
  }
  
  .pagination-wrapper .el-pagination .el-pagination__sizes {
    margin-right: 10px;
  }
  
  .pagination-wrapper .el-pagination .el-pagination__jump {
    margin-left: 10px;
  }
}

@media (max-width: 480px) {
  .pagination-wrapper {
    flex-direction: column;
    gap: 10px;
  }
  
  .pagination-wrapper .el-pagination {
    justify-content: center;
  }
}
</style> 